/*
 * zhangqunshi@126.com
 * 2015-11-18
 */
package com.kris;

import ch.ethz.ssh2.*;
import java.io.File;
import java.io.IOException;

/**
 * 使用SCP上传文件或目录
 *
 * @author kris
 */
public class SCP {

    private final String usr;
    private final String pwd;
    private final String host;

    public SCP(String host, String user, String password) {
        this.usr = user;
        this.pwd = password;
        this.host = host;
    }

    /**
     * 上传一个文件或者目录
     *
     * @param localPath
     * @param remotePath
     * @throws Exception
     */
    public void upload(String localPath, String remotePath) throws Exception {
        Connection con = new Connection(host);
        try {

            con.connect();
            boolean isAuthed = con.authenticateWithPassword(usr, pwd);
            System.out.println("authentication: " + isAuthed);

            File srcFilePath = new File(localPath);
            if (srcFilePath.isDirectory()) {
                uploadDir(con, localPath, remotePath, "0644");
            } else {
                System.out.println("upload " + localPath + " to " + remotePath);
                SCPClient scpClient = con.createSCPClient();
                // 如果远程目录不存在，那么会抛出Error during SCP transfer.
                createDir(con, remotePath);
                scpClient.put(localPath, remotePath);
            }
        } catch (Exception e) {
            System.out.println("Fail to upload " + localPath + " to " + remotePath + ", Error: " + e.getMessage());
            throw e;
        } finally {
            con.close();
        }
    }

    /**
     * 上传一个目录
     *
     * @param conn
     * @param localDir
     * @param remoteDir
     * @param mode
     * @throws IOException
     */
    private void uploadDir(Connection conn, String localDir, String remoteDir,
            String mode) throws IOException {
        File srcLocalDir = new File(localDir);

        String new_dir = remoteDir + File.separator + srcLocalDir.getName();
        createDir(conn, new_dir);

        File[] fs = srcLocalDir.listFiles();
        for (File f : fs) {
            String absPath = f.getAbsolutePath();
            if (f.isDirectory()) {
                uploadDir(conn, absPath, new_dir, mode);
            } else {
                SCPClient client = conn.createSCPClient();
                System.out.println("upload " + absPath + " to " + new_dir);
                client.put(absPath, new_dir, mode);
            }

        }

    }

    /**
     * 在服务器上建立一个目录
     *
     * @param conn
     * @param remoteDir
     * @throws IOException
     */
    private void createDir(Connection conn, String remoteDir) throws IOException {
        Session s = conn.openSession();
        try {
            System.out.println("create dir: " + remoteDir);
            s.execCommand("mkdir -p -m 755 " + remoteDir);
            s.waitForCondition(ChannelCondition.EOF, 0);
        } finally {
            s.close();
        }

    }

}
